package cn.iocoder.boot.service.impl.supplier;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import cn.iocoder.boot.entity.ComponentPrice;
import cn.iocoder.boot.entity.ComponentStock;
import cn.iocoder.boot.enums.SupplierCodeEnum;
import cn.iocoder.boot.service.CallLimitService;
import cn.iocoder.boot.service.ComponentPriceService;
import cn.iocoder.boot.service.ComponentStockService;
import cn.iocoder.boot.service.HttpRequestLogService;
import cn.iocoder.boot.service.impl.SalePriceConfigServiceImpl;
import cn.iocoder.boot.vo.ComplianceVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@Service
@DS("master")
@Slf4j
public class MouserServiceImpl {

    private static final String API_URL = "http://192.168.10.92:8010/mouser.ashx?cmd=enquiry";

    @Resource
    private ComponentStockService componentStockService;

    @Resource
    private ComponentPriceService componentPriceService;

    @Resource
    private CallLimitService callLimitService;

    @Resource
    private SalePriceConfigServiceImpl salePriceConfigService;

    @Resource
    private HttpRequestLogService httpRequestLogService;

    // 昴氏根据库存id合集进行询价
    @PermitAll
    public void query(List<String> models, Map<String, BigDecimal> componentSupplierMap) {
        // 去重处理
        List<String> distinctModels = models.stream()
                .distinct()
                .toList();

        for (String model : distinctModels) {
            queryOne(model, componentSupplierMap);
        }

    }

    // 查询单个，进行更新
    public List<ComponentPrice> queryOne(String model, Map<String, BigDecimal> componentSupplierMap) {
        callLimitService.supplierLimitCall(SupplierCodeEnum.MOUSER.getCode());

        // 发送HTTP请求并获取响应
        String response = sendEnquiryRequest(model);
        log.info("昴氏单个查询API响应: {}", response);
        log.info("{} 昴氏 queryOne API response: {}", model, response);

        // 解析响应并处理数据
        return processSingleEnquiryResponse(response, model, componentSupplierMap);
    }

    /**
     * 发送询价请求的公共方法
     */
    private String sendEnquiryRequest(String model) {
        String encodedModel = URLEncoder.encode(model.replace("＋", "+"), StandardCharsets.UTF_8);
        String postData = "mfc=" + encodedModel;

        try (HttpResponse httpResponse = HttpRequest.post(API_URL)
                .body(postData)
                .execute()) {
            httpRequestLogService.saveHttpRequestLog(API_URL, "Mouser_queryOne", model, httpResponse.body(), httpResponse.getStatus());
            return httpResponse.body();
        }
    }

    /**
     * 处理单个询价响应
     */
    private List<ComponentPrice> processSingleEnquiryResponse(String response, String originalModel,
                                                              Map<String, BigDecimal> componentSupplierMap) {
        JSONObject jsonResponse = JSON.parseObject(response);
        int code = jsonResponse.getIntValue("code");
        List<ComponentPrice> componentPriceList = new java.util.ArrayList<>();
        if (code == 0) {
            JSONArray dataArray = jsonResponse.getJSONArray("data");
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject item = dataArray.getJSONObject(i);
                // 处理价格（乘以1.13）
                processPricing(item);
                ComponentPrice componentPrice = processEnquiryItem(item, componentSupplierMap, originalModel);
                componentPriceList.add(componentPrice);
            }
        } else {
            log.error("单个查询API返回错误代码: {}", code);
        }
        return componentPriceList;
    }

    /**
     * 处理询价项目数据
     */
    private ComponentPrice processEnquiryItem(JSONObject item, Map<String, BigDecimal> componentSupplierMap, String originalModel) {
        ComponentStock stock = new ComponentStock();
        stock.setModel(item.getString("ven_mfc_mode"));
        stock.setKeyword(originalModel);

        stock.setBrand(item.getString("ven_brand"));
        stock.setSpecifications(item.getString("ven_desc_dtl"));
        stock.setStockType(1);
        stock.setSupplierCode(SupplierCodeEnum.MOUSER.getCode());
        stock.setPartnumber(item.getString("ven_partnumber"));
        stock.setUniqueId(SupplierCodeEnum.MOUSER.getCode() + "_" + item.getString("ven_partnumber"));
        String productCompliance = item.getString("ProductCompliance");
        if (StringUtils.isNotBlank(productCompliance)) {
            List<ComplianceVO> productComplianceList = JSONUtil.toList(productCompliance, ComplianceVO.class);
            productComplianceList.stream()
                    .filter(attr -> "ECCN".equals(attr.getComplianceName()))
                    .findFirst()
                    .ifPresent(attr -> stock.setExportControlClassificationNumber(attr.getComplianceValue()));
        }
        stock.setMinNum(StringUtils.isEmpty(item.getString("MinimumOrderQuantity")) ? null :
                Integer.valueOf(item.getString("MinimumOrderQuantity")));


        // 提取封装信息
        String encapsulation = extractEncapsulation(item.getJSONArray("ven_package"));

        JSONArray myPricing = item.getJSONArray("MyPricing");
        JSONArray standardPricing = item.getJSONArray("StandardPricing");

        String saleJson = salePriceConfigService.getSaleJson(
                standardPricing.toJSONString(),
                stock.getModel(),
                "RMB"
        );

        // 构建价格对象
        componentStockService.saveComponentStockOfUniqueKey(stock);
        ComponentPrice componentPrice = new ComponentPrice(
                stock.getUniqueId(),
                myPricing.toJSONString(),
                item.getLong("QuantityAvailable"),
                null,
                encapsulation,
                "RMB",
                stock.getModel(),
                standardPricing.toJSONString(),
                saleJson,
                componentSupplierMap.getOrDefault(SupplierCodeEnum.MOUSER.getCode(), BigDecimal.valueOf(2))
        );
        componentPriceService.createComponentPriceOfUniqueKey(componentPrice);
        componentPrice.setStockInfo(stock);
        return componentPrice;
    }

    /**
     * 提取封装信息
     */
    private String extractEncapsulation(JSONArray packageArray) {
        if (packageArray == null) {
            return "";
        }

        for (int i = 0; i < packageArray.size(); i++) {
            JSONObject packageItem = packageArray.getJSONObject(i);
            if ("封装".equals(packageItem.getString("AttributeName"))) {
                return packageItem.getString("AttributeValue");
            }
        }
        return "";
    }

    /**
     * 处理价格（乘以1.13并保留四位小数）
     */
    private void processPricing(JSONObject item) {
        // 处理MyPricing
        processPricingArray(item.getJSONArray("MyPricing"));
        // 处理StandardPricing
        processPricingArray(item.getJSONArray("StandardPricing"));
    }

    /**
     * 处理价格数组
     */
    private void processPricingArray(JSONArray pricingArray) {
        if (pricingArray == null) {
            return;
        }

        for (int i = 0; i < pricingArray.size(); i++) {
            JSONObject pricingItem = pricingArray.getJSONObject(i);
            BigDecimal price = new BigDecimal(pricingItem.getString("Price"));
            BigDecimal newPrice = price.multiply(new BigDecimal("1.13"))
                    .setScale(4, RoundingMode.HALF_UP);
            pricingItem.put("Price", newPrice);
        }
    }
}
